//
//  IDDObjectCacheManager.m
//  ComJia
//
//  Created by Aslan on 17/02/2017.
//  Copyright © 2017 ComJia. All rights reserved.
//

#import "IDDObjectCacheManager.h"
#import "IDDError+LocalCache.h"

@implementation IDDObjectCacheManager

- (instancetype)init
{
    self = [super initWithRoot:@"obj"];
    if (self) {
    }
    return self;
}

- (BOOL)canSupportObject:(id)object
{
    return !object || [object conformsToProtocol:@protocol(NSCoding)];
}

- (BOOL)saveObject:(id)object atPath:(NSString *)path error:(IDDError *__autoreleasing *)error
{
    if (error) {
        *error = nil;
    }
    BOOL success = [NSKeyedArchiver archiveRootObject:object toFile:path];
    if (!success) {
        if (error) {
            *error = cacheErrorWithCode(IDDErrorCacheDomainArchiveFailure, nil);
        }
    }
    return success;
}

- (id)restoreObjectAtPath:(NSString *)path error:(IDDError *__autoreleasing *)error
{
    if (error) {
        *error = nil;
    }
    id object = nil;
    @try {
        object = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
        return object;
    } @catch (NSException *exception) {
        if ([exception.name isEqualToString:NSInvalidArgumentException]) {
            if (error) {
                *error = cacheErrorWithCode(IDDErrorCacheDomainUnarchiveFailure, nil);
            }
            return nil;
        } else {
            @throw exception;
        }
    }
}

@end
